package cn.jietuo.juc.c_009_interview2;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zhangx & jietuo_zx@163.com
 * @version 1.0
 * @date 2020/5/8
 * @description: 题目见package-info
 * 渣渣，写的个啥啊。。
 *
 */
public class T01 {

    static class MyContainer {

        private int size;

        private List<String> container = null;

        public MyContainer(int size) {
            this.size = size;
            container = new ArrayList<>(size);
        }

        private synchronized boolean put(String param) {
            if (container.size() < size) {
                container.add(param);
                size++;
                return true;
            } else {
                System.out.println("容器已满");
                return false;
            }
        }

        private synchronized String get() {
            if (container.size() > 0) {
                String remove = container.remove(0);
                size--;
                return remove;
            } else {
                System.out.println("没有数据了");
                return null;
            }
        }

        private Integer getCount() {
            return container.size();
        }
    }

    public static void main(String[] args) {
        MyContainer myContainer = new MyContainer(20);

        // 两个生产线程
        new Thread(() -> {
            for (int i = 0; i < 100; i++) {
                boolean put = myContainer.put("t1--" + i);
                if (put) {
                    System.out.println("t1 添加:t1--" + i);
                }
            }
        }, "t1").start();

        new Thread(() -> {
            for (int i = 0; i < 100; i++) {
                boolean put = myContainer.put("t2--" + i);
                if (put) {
                    System.out.println("t2 添加:t2--" + i);
                }
            }
        }, "t2").start();

        Thread[] threads = new Thread[10];
        for (int i = 0; i < 10; i++) {
            threads[i] = new Thread(() -> {
                for (int j = 0; j < 100; j++) {
                    String s = myContainer.get();
                    if (s != null) {
                        System.out.println(Thread.currentThread().getName() + "--拿到数据：" + s);
                    }
                }
            });
        }

        for (int i = 0; i < 10; i++) {
            threads[i].start();
        }
    }
}
